package com.example.thirdhomework

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class FourthActivity : AppCompatActivity() {
    private lateinit var textView: TextView
    private var timeElapsedInMillis: Long = 0
    private val handler = Handler(Looper.getMainLooper())
    private lateinit var runnable: Runnable
    private var isRunning = false
    private var wasRunning = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if(savedInstanceState != null){
            timeElapsedInMillis = savedInstanceState.getLong("timeElapsedInMillis")
            isRunning = savedInstanceState.getBoolean("isRunning")
            wasRunning = savedInstanceState.getBoolean("wasRunning")
        }

        setContentView(R.layout.activity_fourth)
        textView = findViewById(R.id.textView2)
        val startButton: Button = findViewById(R.id.button_start)
        val stopButton: Button = findViewById(R.id.button_stop)
        val restartButton: Button = findViewById(R.id.button_restart)

        startButton.setOnClickListener {
            startTimer()
        }
        stopButton.setOnClickListener {
            stopTimer()
        }
        restartButton.setOnClickListener {
            restartTimer()
        }

    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putLong("timeElapsedInMillis", timeElapsedInMillis)
        outState.putBoolean("isRunning", isRunning)
        outState.putBoolean("wasRunning", wasRunning)
    }

    private fun startTimer() {
//        if (!isRunning) {
            isRunning = true
            runnable = object : Runnable {
                override fun run() {
                    if (isRunning) {
                        timeElapsedInMillis += 1000
                        updateTextView()
                        handler.postDelayed(this, 1000)
                    }
                }
            }
            handler.post(runnable)
//        }
    }

    private fun stopTimer() {
        isRunning = false
        handler.removeCallbacks(runnable)
    }

    private fun restartTimer() {
        timeElapsedInMillis = 0
        isRunning = false
        handler.removeCallbacks(runnable)
        updateTextView()
    }

    private fun updateTextView() {
        val minutes = (timeElapsedInMillis / 1000) / 60
        val seconds = (timeElapsedInMillis / 1000) % 60
        val hours = (timeElapsedInMillis / 1000) / 3600
        val timeFormatted = String.format("%02d:%02d:%02d",hours, minutes, seconds)
        textView.text = timeFormatted
    }
}